import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/models/report/studentOverview.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:intl/intl.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import '../../themes/pageStyles.dart';

// ignore: must_be_immutable
class StudentsReportDataGrid extends StatelessWidget {
  StudentsReportDataGrid(
      {Key? key, required this.studentOverviewItems, required this.classId});

  final GlobalKey<SfDataGridState> studentGridkey =
      GlobalKey<SfDataGridState>();
  List<StudentOverview> studentOverviewItems;
  String classId;
  DataGridController _dataGridController = DataGridController();
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build StudentsReportDataGrids');

    return this.studentOverviewItems.isNotEmpty
        ? Column(children: [Expanded(child: _buildDataGrid())])
        : Center(child: Text('Students not available ...'.tr));
  }

  Container _buildDataGrid() {
    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        decoration: _pageStyles.dataGridForground(),
        margin: EdgeInsets.all(12.0),
        child: SfDataGrid(
          source: StudentDataGridSource(
              items: studentOverviewItems, classId: classId),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          key: studentGridkey,
          showCheckboxColumn: false,
          rowsPerPage: 15,
          allowSorting: true,
          allowFiltering: true,
          allowTriStateSorting: true,
          allowSwiping: true,
          navigationMode: GridNavigationMode.row,
          controller: _dataGridController,
          columns: <GridColumn>[
            GridColumn(
              columnName: 'UserName',
              width: 180,
              label: buildDataGridColumnLabel('UserName'),
            ),
            GridColumn(
              width: 160,
              columnName: 'FirstName',
              label: buildDataGridColumnLabel('FirstName'),
            ),
            GridColumn(
              columnName: 'LastName',
              width: 160,
              label: buildDataGridColumnLabel('LastName'),
            ),
            GridColumn(
              columnName: 'Level',
              //allowFiltering: false,
              width: 120,
              label: buildDataGridColumnLabel('Level'),
            ),
            GridColumn(
              columnName: 'LevelPercentage',
              width: 180,
              allowFiltering: false,
              label: buildDataGridColumnLabel('LevelPercentage'),
            ),
            GridColumn(
              columnName: 'ReadingTimes',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('Books/Times of Reading'),
            ),
            GridColumn(
              columnName: 'ReadingBooks',
              width: 80,
              allowFiltering: false,
              visible: false,
              label: buildDataGridColumnLabel('ReadingBooks'),
            ),
            GridColumn(
              columnName: 'Quizzes',
              allowFiltering: false,
              width: 130,
              label: buildDataGridColumnLabel('Quizzes'),
            ),
            GridColumn(
              columnName: 'LastLogin',
              width: 180,
              allowFiltering: false,
              label: buildDataGridColumnLabel('LastLogin'),
            ),
            GridColumn(
              columnName: 'ClassId',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('ClassId'),
            ),
          ],
        ),
      ),
    );
  }
}

class StudentDataGridSource extends DataGridSource {
  StudentDataGridSource(
      {required List<StudentOverview> items, required String classId}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<String>(
                  columnName: 'Level', value: dataGridRow.playerLevel),
              DataGridCell<int>(
                  columnName: 'LevelPercentage',
                  value: dataGridRow.levelPercentage),
              DataGridCell<int>(
                  columnName: 'ReadingTimes', value: dataGridRow.readTimes),
              DataGridCell<int>(
                  columnName: 'ReadingBooks', value: dataGridRow.readBooks),
              DataGridCell<int>(
                  columnName: 'Quizzes', value: dataGridRow.quizTimes),
              DataGridCell<int>(
                  columnName: 'LastLogin',
                  value: dataGridRow.lastLoggedIn != null
                      ? dataGridRow.lastLoggedIn
                      : 0),
              DataGridCell<String>(columnName: 'ClassId', value: classId),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'UserName') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(
                        Get.context!, '/reports/studentPersonal',
                        arguments: [
                          row
                              .getCells()
                              .where(
                                  (element) => element.columnName == 'ClassId')
                              .first
                              .value
                              .toString(),
                          dataGridCell.value
                        ]);
                  },
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.textTheme.titleLarge,
                    overflow: TextOverflow.fade,
                  ),
                ));
          } else if (dataGridCell.columnName == 'LevelPercentage') {
            int process = dataGridCell.value ?? 0;
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: LinearPercentIndicator(
                animation: true,
                lineHeight: 18.0,
                animationDuration: 1000,
                percent: process.toDouble() / 100,
                center: Text(
                  "$process%",
                  style: TextStyle(
                      fontSize: 12.0,
                      fontFamily: 'Montserrat',
                      color: Colors.black),
                ),
                progressColor: Get.isDarkMode
                    ? AppTheme.colors.primaryLight.withOpacity(0.9)
                    : Get.theme.primaryColor,
                barRadius: Radius.circular(16),
                backgroundColor: Get.isDarkMode
                    ? Get.theme.primaryColor.withOpacity(0.9)
                    : Colors.black.withOpacity(0.1),
              ),
            );
          } else if (dataGridCell.columnName == 'LastLogin') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 12.0),
                  child: Text(
                    DateFormat('MM/dd/yyyy kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 12.0),
                  child: Text(
                    ' - ',
                    overflow: TextOverflow.fade,
                  ));
            }
          } else if (dataGridCell.columnName == 'ReadingTimes') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 12.0),
                child: Text(
                  row
                          .getCells()
                          .where(
                              (element) => element.columnName == 'ReadingBooks')
                          .first
                          .value
                          .toString() +
                      '/' +
                      dataGridCell.value.toString(),
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 12.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
